package com.xhwl.logistics.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.enums.vehicle.DeviceStatusEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.cent.device.Device;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.pojo.cent.vehicle.VehcArea;
import com.xhwl.common.pojo.cent.vehicle.VehcParkingLot;
import com.xhwl.common.pojo.cent.vehicle.VehcPassage;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.query.cent.vehicle.DeviceQuery;
import com.xhwl.common.vo.cent.vehicle.PlaceVO;
import com.xhwl.logistics.bo.cent.DeviceBO;
import com.xhwl.logistics.converter.mapstruct.CentDeviceConverter;
import com.xhwl.logistics.dao.VehcAreaDao;
import com.xhwl.logistics.dao.VehcParkingLotDao;
import com.xhwl.logistics.dao.VehcPassageDao;
import com.xhwl.logistics.service.cent.IDeviceService;
import com.xhwl.logistics.service.cent.IProjectService;
import com.xhwl.logistics.service.IVehcDeviceService;
import com.xhwl.logistics.util.IdWorker;
import com.xhwl.common.vo.cent.vehicle.DeviceVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;
import java.util.stream.Collectors;

import static org.springframework.beans.BeanUtils.copyProperties;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Lu.Aaron
 * @since 2021-02-08
 */
//@Service
public class VehcDeviceServiceImpl implements IVehcDeviceService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private VehcParkingLotDao vehcParkingLotDao;
    @Autowired
    private VehcAreaDao vehcAreaDao;
    @Autowired
    private VehcPassageDao vehcPassageDao;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private CentDeviceConverter centDeviceConverter;
    @Override
    public void add(DeviceVO deviceVO) {

    }

    @Override
    public void edit(DeviceVO deviceVO, Short industryId) {
        DeviceDTO deviceDTO = new DeviceDTO();
        BeanUtils.copyProperties(deviceVO, deviceDTO);
        deviceService.update(industryId, deviceDTO);
    }

    @Override
    public Page<DeviceDTO> devicePage(DeviceQuery deviceQuery, Short industryId) {
        if (Objects.isNull(deviceQuery.getProjectId())) {
            throw new BusinessException("缺少必要参数：projectId");
        }
        if (Objects.isNull(deviceQuery.getQueryLevel())) {
            throw new BusinessException("缺少必要参数：queryLevel");
        }
        //TODO 1.构建设备中台查询实体
        DevicePageQuery devicePageQuery = new DevicePageQuery();
        devicePageQuery.setProjectIdList(deviceQuery.getProjectId());
        devicePageQuery.setName(deviceQuery.getName());
        DeviceStatusEnum status = deviceQuery.getStatus();
        String orderColumn = deviceQuery.getOrderColumn();
        Boolean orderAsc = deviceQuery.getOrderAsc();
        if (null!=orderColumn) {
            devicePageQuery.setOrderColumn(orderColumn);
            devicePageQuery.setOrderAsc(orderAsc);
        }

        if (null!=status) {
            devicePageQuery.setOnlineStatus(status.getKey());
        }

        if (null!=deviceQuery.getStatus()) {
            devicePageQuery.setOnlineStatus(deviceQuery.getStatus().getKey());
        }
        devicePageQuery.setCurrent(Long.valueOf(deviceQuery.getCurrent()));
        // 2代表车行系统（来源与设备中台）

        devicePageQuery.setCategoryId(3);
        devicePageQuery.setSize(Long.valueOf(deviceQuery.getPageSize()));
        //devicePageQuery.setQueryLevel(deviceQuery.getQueryLevel());
        //TODO 2.调用设备中台查询车行设备
        Page<DeviceDTO> deviceDTOPage = deviceService.listPageDevice(industryId, devicePageQuery);
        List<DeviceDTO> records = deviceDTOPage.getRecords();
        Set<Integer> projectIdSet = records.stream().map(r -> r.getProductId()).collect(Collectors.toSet());
        List<Integer> projectIdList = new ArrayList<>(projectIdSet);
        ProjectQuery projectQuery = new ProjectQuery();
        projectQuery.withIdList(projectIdList);
        List<Project> projects = projectService.list(projectQuery, null);
        //TODO 3.在records获取对应的车场、区域、通道对应的orgId的Set集合
        HashSet<Integer> parkingLotOrdIds = new HashSet<>();
        HashSet<Integer> areaOrdIds = new HashSet<>();
        HashSet<Integer> passageOrdIds = new HashSet<>();
        records.forEach(r->{
            List<Organization> organizations = r.getOrganizations();
            if (null!=organizations&&!organizations.isEmpty()) {
                organizations.forEach(organization -> {
                    if (organization.getType().equals(OrganizationTypeEnum.PARKING_LOT)) {
                        parkingLotOrdIds.add(organization.getId());
                    }else if(organization.getType().equals(OrganizationTypeEnum.PARKING_AREA)){
                        areaOrdIds.add(organization.getId());
                    }else if(organization.getType().equals(OrganizationTypeEnum.PASSAGE)){
                        passageOrdIds.add(organization.getId());
                    }
                });
            }
            //TODO 4.将从主数据查询得到的projects中获取projectName
            projects.forEach(project -> {
                if (r.getProjectId().equals(project.getId())) {
                    r.setProjectName(project.getName());
                }
            });

        });

        //TODO 5.通过上述获取的Set集合分别查询车场、区域 、通道, 转化成LIst<PlaceVO> 用于前端显示级联定位
        List<VehcParkingLot> vehcParkingLots=new ArrayList<>();
        if (!parkingLotOrdIds.isEmpty()) {
            vehcParkingLots = vehcParkingLotDao.selectList(new QueryWrapper<VehcParkingLot>().in("org_id", parkingLotOrdIds));
        }
        List<VehcArea> vehcAreas =new ArrayList<>();
        if (!areaOrdIds.isEmpty()) {
            vehcAreas = vehcAreaDao.selectList(new QueryWrapper<VehcArea>().in("org_id", areaOrdIds));
        }
        List<VehcPassage> vehcPassages =new ArrayList<>();
        if (!passageOrdIds.isEmpty()) {
            vehcPassages = vehcPassageDao.selectList(new QueryWrapper<VehcPassage>().in("org_id", passageOrdIds));
        }


        List<VehcParkingLot> finalVehcParkingLots = vehcParkingLots;
        List<VehcArea> finalVehcAreas = vehcAreas;
        List<VehcPassage> finalVehcPassages = vehcPassages;
        records.forEach(r->{
            List<Organization> organizations = r.getOrganizations();
            if (null!=organizations) {
                List<PlaceVO> placeVOList = new ArrayList<>();

                organizations.forEach(organization -> {
                    PlaceVO placeVO = new PlaceVO();
                    if (organization.getType().equals(OrganizationTypeEnum.PARKING_LOT)) {
                        finalVehcParkingLots.forEach(vehcParkingLot -> {
                            if (organization.getId().equals(vehcParkingLot.getOrgId())) {
                                placeVO.setId(vehcParkingLot.getId());
                                placeVO.setName(vehcParkingLot.getName());
                                placeVO.setOrganizationTypeEnum(OrganizationTypeEnum.PARKING_LOT);
                                placeVOList.add(placeVO);
                            }
                        });
                    }else if(organization.getType().equals(OrganizationTypeEnum.PARKING_AREA)){
                        finalVehcAreas.forEach(vehcArea -> {
                            if (organization.getId().equals(vehcArea.getOrgId())) {
                                placeVO.setId(vehcArea.getId());
                                placeVO.setName(vehcArea.getName());
                                placeVO.setOrganizationTypeEnum(OrganizationTypeEnum.PARKING_AREA);
                                placeVOList.add(placeVO);
                            }
                        });
                    }else if(organization.getType().equals(OrganizationTypeEnum.PASSAGE)){
                        finalVehcPassages.forEach(vehcPassage -> {
                            if (organization.getId().equals(vehcPassage.getOrgId())) {
                                placeVO.setId(vehcPassage.getId());
                                placeVO.setName(vehcPassage.getName());
                                placeVO.setOrganizationTypeEnum(OrganizationTypeEnum.PASSAGE);
                                placeVOList.add(placeVO);
                            }
                        });
                    }
                });
                r.setPlaceVOList(placeVOList);
            }

        });

        return deviceDTOPage;
    }
    @Override
    public List<Device> listdevice(DevicePageQuery devicePageQuery, Short industryId) {
        List<DeviceDTO> deviceDTOList = deviceService.listDevice(industryId, devicePageQuery);
        List<DeviceBO> deviceBOList= centDeviceConverter.deviceDTOList2DeviceBOList(deviceDTOList);
        List<Device> device=centDeviceConverter.deviceBOList2DeviceList(deviceBOList);
        return device;
    }
}
